﻿/*

AjaxDataProvider is (as it's name implies) a data provider for liteGrid
that sends/receives data via AJAX.

Author: MBH
DateAuthored: 7/17/09  
*/

//A full-featured AJAX-JSON data provider for liteGrid.  Its goal is to 
//support all the data maniplation requirements for all built-in modules.
function AjaxDataProvider(options) {

	var base = this;
	
	//URLs for AJAX requests
	base.rootDataUrl = (options.rootDataUrl || "");
	base.childDataUrl = (options.childDataUrl || "");
	base.saveDataUrl = (options.saveDataUrl || "");
	base.saveCellUrl = (options.saveCellUrl || "");
	base.deleteDataItemsUrl = (options.deleteDataItemsUrl || "");

	//Make sure JSON is available
	if (!$.toJSON) {
		console.error("JSON object is not set, please be sure the JSON plug-in for jQuery has been loaded.");
		return;
	}

	//Optional call-back that will be run by whatever liteGrid instance this is attached to.
	base.initialize = function(liteGrid, options) {

		//Used to raise data events.
		base.liteGrid = liteGrid;
		//Needed for some operations
		base.keyField = options.rowIdColumn;
	}

	//Utility method for doing AJAX requests.
	base.doAjax = function(success, error, options) {

		if (!success) success = function() { };
		if (!error) error = function() { };

		base.liteGrid.$el.trigger("dataLoading");

		var ajaxOptions = $.extend({},
		{
			success: function(data) {
				success(data);
			},
			error: error,
			complete: function() {
				base.liteGrid.$el.trigger("dataLoaded");
			},
			dataType: "json",
			cache: false
		}, options);

		$.ajax(ajaxOptions);
	}

	//Gets data from the server.
	//This takes two parameters: a callback for success, and a callback for errors.
	base.getData = function(success, error) {

		base.doAjax(success, error, { type: "GET", url: base.rootDataUrl });
	}

	//Gets children of the specified item.
	base.getChildData = function(parentId, success, error) {

		base.doAjax(success, error, { type: "GET", url: base.childDataUrl, data: { parentId: parentId} });
	}

	//Posts the data back to the server.
	base.saveData = function(dataItems, success, error) {

		base.doAjax(success, error, { type:"POST", url: base.saveDataUrl,
			data: $.toJSON(dataItems), contentType: 'application/json; charset=utf-8'
		});
	}

	//Saves the value of a single cell back to the server.
	base.saveCell = function(id, column, value, success, error) {

		var data = {};
		data[base.keyField] = id;
		data[column] = value;

		base.doAjax(success, error, { type: "POST", url: base.saveCellUrl,
			data: data
		});
	}

	//Deletes the specified data item
	base.deleteDataItems = function(dataItemIds, success, error) {

		var data = {};
		data[base.keyField + "s"] = dataItemIds;

		base.doAjax(success, error, { url: base.deleteDataItemsUrl, data: data,
			contentType: "application/json; charset=utf-8"
		});
	}
}